﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.IO;
using System.Text;
using Excel;

namespace OrderAggregator.InputFormats.GlobalMarket
{
	/// <summary>
    /// Формат ООО "Глобал-Маркет"
	/// </summary>
    public class GlobalMarketFormat : Excel.BaseExcelFormat
	{
        public readonly static GlobalMarketFormat Instance = new GlobalMarketFormat();

        private GlobalMarketFormat()
        {
        }

		/// <summary>
		/// Parse
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="getStream"></param>
		/// <returns></returns>
		public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
		{
            if (!string.Equals(System.IO.Path.GetExtension(filePath), dotXLS, StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
            
            var dataSet = ReadAsDataset(getStream());

            if (dataSet == null || dataSet.Tables.Count == 0)
            {
                return null;
            }

            var table = dataSet.Tables[0];


            string number, client;
            DateTime date;
            int startRowData;
            if (!TryParseNumberAndDateAndClient(table, out number, out date, out client, out startRowData))
            {
                return null;
            }


            var order = new BaseOrder();
            order.Id = number;
            order.ReceiveTime = date;
            order.Client = client;

            var orderRows = GetOrderRows(table, startRowData);

            foreach (var orderDataRow in orderRows)
            {
                var orderRow = new BaseOrderRow();
                orderRow.ProductCode = orderDataRow[1].ToString();
                orderRow.ProductName = orderDataRow[2].ToString();
                orderRow.Count = decimal.Parse(orderDataRow[5].ToString(), BaseOrderFormat.RuCulture);
                orderRow.UnitName = (string.Equals(orderDataRow[3].ToString(), "Весовой", StringComparison.InvariantCultureIgnoreCase)) ? UnitKg : UnitPcs;                  

                order.OrderRows.Add(orderRow);
            }
			return order;                     
        }
       
        private bool TryParseNumberAndDateAndClient(DataTable table, out string number, out DateTime date, out string client, out int startRowData)
        {
            number = string.Empty;            
            date = DateTime.MinValue;
            client = string.Empty;
            var client_name = string.Empty;
            var client_addres = string.Empty;

            var header = string.Empty;
            var countField = 0;
            int i;

            for (i = 0; i < table.Rows.Count && countField < 3; i++)          
            {
                DataRow nextRow = null;
                if (i + 1 < table.Rows.Count)
                {
                    nextRow = table.Rows[i + 1];
                }
                else 
                {
                    break;
                }

                for (var j = 0; j < table.Columns.Count && countField < 3; j++)
                {
                    header = table.Rows[i][j] as string;

                    string nextRowCell = nextRow[j] == null ? string.Empty : nextRow[j].ToString();

                    if (!string.IsNullOrEmpty(header))
                    {

                        if (string.IsNullOrEmpty(number))
                        { 
                            if (header.Contains("Номер заявки"))
                            {
                                number = nextRowCell.Trim();
                                countField++;
                            }
                        }
                        else 
                        {
                            if (string.IsNullOrEmpty(client))
                            {

                                if (header.Contains("Юридическое лицо"))
                                {
                                    client_name = nextRowCell.Trim();
                                }
                                else
                                {
                                    if (header.Contains("Адрес получателя"))
                                    {
                                        client_addres = nextRowCell.Trim();
                                    }
                                }

                                if (!string.IsNullOrEmpty(client_name) && !string.IsNullOrEmpty(client_addres))
                                {
                                    client = client_name + " " + client_addres;
                                    countField++;
                                }

                            }
                            else
                            {
                                if (header.Contains("Дата заявки"))                            
                                {
                                    if (!string.IsNullOrEmpty(nextRowCell) && !DateTime.TryParse(nextRowCell, out date))
                               
                                    {
                                        date = DateTime.FromOADate(double.Parse(nextRowCell));                               
                                    }                                
                                    countField++;
                            
                                }
                            }                        
                        }                                                               
                    }  
                }
            }
            startRowData = i;

            if (countField < 3)
            {
                return false;
            }
          
            return true;
        }

        private static List<DataRow> GetOrderRows(DataTable table, int startRowData)
        {
            var rows = new List<DataRow>();
            var startRow = startRowData;
            for (var i = startRow; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                if (!string.IsNullOrEmpty(row[0].ToString()))
                {
                    var strColmn1 = row[0] as string;                    
                    var strColmn3 = row[2] as string;

                    if (string.Equals(strColmn1, "Порядковый номер", StringComparison.InvariantCultureIgnoreCase) &&                       
                        string.Equals(strColmn3, "Полное наименование товара (наименование - торговая марка - жирность - граммовка/литраж)"))
                    {
                        startRow = i + 2;
                        break;
                    }
                }
            }

            if (startRow == startRowData)
            {
                return rows;
            }

            for (int i = startRow; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];

                var strColmn1 = row[1] as string;

                if (string.IsNullOrEmpty(strColmn1))
                {
                    break;
                }

                rows.Add(row);
            }

            return rows;
        }
	}
}
